from pprint import pprint

from django.http import HttpResponse, HttpResponseBadRequest

from common.sql_constant_enum import project_id_corresponding
from common.sql_instance_project_data import *
from utils.cursorHandler_aiomysql import cursor
from common.sql_instance_project import *
from datetime import date
from common.constant import position_program_ids, map_program_ids, deliver__program_ids
from utils.normal_simple_function import serialize_json_dumps, serialize_json_date_type
# Create your views here.


# 一级页面-项目详情页：各个项目的详情
def projectIterationExtension(request):
    """
        项目迭代版本详情
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        tag_type = int(request.GET.get('tag_type', 0))

        # 全部
        if tag_type == 0:
            project_ids = tuple(each['id'] for each in cursor.search_alone(all_project_name_search_sql))
        # 定位
        elif tag_type == 1:
            project_ids = tuple(each[0] for each in position_program_ids)
        # 地图
        elif tag_type == 2:
            project_ids = tuple(each[0] for each in map_program_ids)
        # 交付
        elif tag_type == 3:
            project_ids = tuple(each[0] for each in deliver__program_ids)
        # 项目所有的迭代版本(sprint)数据
        project_version_result_sql = construct_project_version_statistics(project_ids)
        print(project_version_result_sql)
        project_version_data: list(dict) = cursor.search_alone(project_version_result_sql)
        print(f'project_version_data: {project_version_data}')

        project_testtask_ids: dict = {each['id']: index for index, each in enumerate(project_version_data)}
        # 查询Bug数据
        project_Bug_data: list(dict) = cursor.search_alone(construct_project_Bug_statistics(project_ids))
        print(f'project_Bug_data: {project_Bug_data}')
        project_Bug_ids: dict = {each['id']: index for index, each in enumerate(project_Bug_data)}
        project_unsolved_Bug_data: list(dict) = cursor.search_alone(construct_project_unsolved_Bug_statistics(project_ids))
        print(f'project_Bug_data: {project_Bug_data}')
        project_unsolved_Bug_ids: dict = {each['id']: index for index, each in enumerate(project_unsolved_Bug_data)}
        json_returns = {'data': {'iteration_version_status_extension': []}}
        for project_index, project_id in enumerate(project_ids):
            # 判断测试单是否存在
            if project_id in project_testtask_ids.keys():
                now_task = project_version_data[project_testtask_ids[project_id]]
            else:
                now_task = {}
            # 判断Bug的统计结果是否存在
            if project_id in project_Bug_ids.keys():
                now_bug = project_Bug_data[project_Bug_ids[project_id]]
            else:
                now_bug = {}
            # 判断历史未解决Bug是否存在
            # print(project_unsolved_Bug_data)
            if project_id in project_unsolved_Bug_ids.keys():
                now_unsolved = project_Bug_data[project_unsolved_Bug_ids[project_id]]
            else:
                now_unsolved = {}
            if not now_task.get('name', ''):
                continue
            # 更新测试单数据
            json_returns['data']['iteration_version_status_extension'].append(
                    {
                        "project_id": project_id,
                        "project_name": now_task.get('name', ''),
                        "project_collection_name": now_task.get('name', ''),
                        "iteration_num": now_task.get('total', 0),
                        "project_status_running": now_task.get('doing', 0),
                        "project_status_blocked": now_task.get('suspended', 0) + now_task.get('wait', 0),
                        "project_status_done": now_task.get('closed', 0),
                        "version_bug_num": {
                            "unsolved": now_bug.get('active', 0),
                            "created": now_bug.get('total', 0),
                            "solved": now_bug.get('resolved', 0),
                            "closed": now_bug.get('closed', 0)
                        },
                        "history_unsolved_bug_total": now_unsolved.get('count', 0),
                        "project_progress": round((now_task.get('done', -1) / now_task.get('total', -1) if now_task.get('total', -1) else 0) * 100, 2) #
                    }
            )
        else:
            json_returns['data']['tag_type'] = tag_type
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')




# 二级页面-由项目跳转到子系统详情页
def subsystemIterationExtension(request):
    """
        项目子系统迭代详情
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数

        project_id = int(request.GET.get('project_id', -1))
        subsystem_detail_rusult = [{}]
        if project_id > 0:
            # 查询所有的子系统
            subsys_ids: list(dict) = cursor.search_alone(construct_sql_get_all_subsys_by_project_id(project_id))
            # 数据结果转换
            subsys_id_name: dict = {each['id']: each['name']  for each in subsys_ids}
            pprint(subsys_ids)
            # 查询项目下的子系统的测试单的情况
            subsystem_detail_rusult: list(dict) = cursor.search_alone(construct_sql_subsystem_detail(tuple(subsys_id_name.keys())))
            # print('-------------------------', subsystem_detail_rusult)
            # 查询项目下各个子系统的历史未解决Bug

        json_returns = {
            "data": {
                "subsystem_version_extension": [
                    {
                        "subsystem_id": each_subsys.get('subsys_id', -1),
                        "subsystem_name": each_subsys.get('pj_name', ''),
                        "online_version": each_subsys.get('task_name', ''),
                        "current_test_version": each_subsys.get('task_name', ''),
                        "plan_deadline": serialize_json_date_type(each_subsys.get('plan_deadline', '')),
                        "history_unsolved_bug_total": cursor.search_alone(construct_sql_subsystem_unsolved_bug_statistics(each_subsys.get('subsys_id')))[0].get('count', -1),
                        "this_day_bug_add": cursor.search_alone(construct_sql_subsystem_unsolved_bug_daily_increase(each_subsys.get('subsys_id')))[0].get('count', -1),
                        "test_leader": each_subsys.get('testleader', ''),
                        "test_status": each_subsys.get('status', ''),
                        "remark": each_subsys.get('desc', ''),
                    } for each_subsys in subsystem_detail_rusult
                ],
                "tag_type": 0
            }
        }
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



# 二级页面-由子系统切换到图表页：Bug趋势图表
def subsystemBugPlot(request):
    """
       项目子系统Bug趋势曲线图 & 统计直方图
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        subsystem_id = int(request.GET.get('subsystem_id', -1))
        date_range = int(request.GET.get('date_range', 7))
        month_num = int(request.GET.get('month_num', 6))
        print(f'requrest params: {subsystem_id, date_range, month_num}')
        json_returns = {"data": {"system_version_extension": [], "date_range": date_range, "subsystem_id": subsystem_id, "month_num":month_num}}
        if subsystem_id > 0:
            for each_index in range(month_num -1, -1, -1):
                # 当前月份
                first_mouth_num = date.today().month - each_index
                # 指定的子系统获取每个月新增的Bug数据
                each_mouth_add_data = cursor.search_alone(construct_subsystem_bug_each_mouth_add_histogram_sql(subsystem_id, first_mouth_num))
                # 指定的子系统获取每个月关闭的Bug数据
                each_mouth_closed_data = cursor.search_alone(construct_subsystem_bug_each_mouth_closed_line_sql(subsystem_id, first_mouth_num))
                # 数据组装
                json_returns['data']['system_version_extension'].append(
                    {
                        "mouth": f"{first_mouth_num if first_mouth_num > 0 else (first_mouth_num + 12)}月",
                        "Bug_trend_histogram_add_num": each_mouth_add_data[0]['count'],
                        "Bug_trend_line_closed_num": each_mouth_closed_data[0]['count']
                    }
                )
        else:
            return HttpResponseBadRequest(content=b'request is a bad request')
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



# 二级页面-由子系统切换到图表页：迭代版本趋势图表
def subsystemIterationPlot(request):
    """
       项目子系统迭代版本趋势图表
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        subsystem_id = int(request.GET.get('subsystem_id', -1))
        date_range = int(request.GET.get('date_range', 7))
        month_num = int(request.GET.get('month_num', 6))
        print(f'requrest params: {subsystem_id, date_range, month_num}')
        # 返回数据初始化
        json_returns = {"data": {"subsystem_version_extension": [], "date_range": date_range, "subsystem_id": subsystem_id, "month_num":month_num}}
        if subsystem_id > 0:
            for each_index in range(month_num -1, -1, -1):
                # 当前月份
                first_mouth_num = date.today().month - each_index
                # 指定的子系统获取每个月新增的Bug数据
                each_mouth_add_data = cursor.search_alone(
                    construct_testtask_each_mouth_add_histogram_sql(subsystem_id, first_mouth_num))
                # 指定的子系统获取每个月关闭的Bug数据
                each_mouth_closed_data = cursor.search_alone(
                    construct_testtask_each_mouth_closed_line_sql(subsystem_id, first_mouth_num))
                # 数据组装
                json_returns['data']['subsystem_version_extension'].append(
                    {
                        "mouth": f"{first_mouth_num if first_mouth_num > 0 else (first_mouth_num + 12)}月",
                        "Bug_trend_histogram_add_num": each_mouth_add_data[0]['count'],
                        "Bug_trend_line_closed_num": each_mouth_closed_data[0]['count']
                    }
                )
        else:
            return HttpResponseBadRequest(content=b'request is a bad request')
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request !!!!')



# 三级页面-子系统详情页：某个项目的子系统的迭代版本详情
def subsystemIterationVersionExtension(request):
    """
        "一个子系统对应多个迭代版本，迭代版本包含多个测试单"
        某个项目的子系统的迭代版本包含的测试单统计的详情
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        subsystem_id = int(request.GET.get('subsystem_id', -1))
        print(f'requrest params: {subsystem_id}')
        # 返回数据初始化
        json_returns = {
            "data": {"iteraction_version_extension": [], "subsystem_id": subsystem_id}}
        if subsystem_id > 0:
            #
            for each_iteration in cursor.search_alone(construct_subsystem_all_iteration_version_detail(subsystem_id)):
                testtask_each_status_results = \
                cursor.search_alone(construct_subsystem_testtask_status_statistics(each_iteration['version_id']))[0]
                done_status_num = testtask_each_status_results.get('done', 0)
                all_status_num = testtask_each_status_results.get('total', 1)
                # 指定的子系统获取每个月新增的Bug数据
                # 数据组装
                json_returns['data']['iteraction_version_extension'].append(
                    {
                        "version_id": each_iteration['version_id'],
                        "version_name": each_iteration['name'],
                        "plan_cycle": [serialize_json_date_type(each_iteration['start_date']), serialize_json_date_type(each_iteration['end_date'])],
                        "plan_date_duration": each_iteration['days'],
                        "dev_leader": each_iteration['RD'],
                        "test_leader": each_iteration['QD'],
                        "unsolved_bug_total": cursor.search_alone(construct_version_id_unsolved_bugs(each_iteration['version_id']))[0].get('count', 0),
                        "this_day_bug_add": cursor.search_alone(construct_version_id_daily_add_bugs(each_iteration['version_id'], last_day=0))[0].get('count', 0),
                        "execute_progress": round((done_status_num / all_status_num if all_status_num else 1) * 100, 2),
                        "execute_status": each_iteration['status'],
                        "remark": each_iteration['desc']
                    }
                )
        else:
            return HttpResponseBadRequest(content=b'request is a bad request')
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request !!!!')



# 三级页面-子系统详情页切换到：迭代版本Bug趋势图表
def IterationBugPlot(request):
    """
        子系统迭代版本Bug趋势曲线图 & 直方图
    :param request:
    :return:
    """

    if request.method == 'GET':
        # 获取get请求带的参数
        version_id = int(request.GET.get('version_id', -1))
        print(f'requrest params: {version_id}')
        date_range = int(request.GET.get('date_range', 7))
        month_num = int(request.GET.get('month_num', 6))
        print(f'requrest params: {version_id, date_range, month_num}')
        json_returns = {
            "data": {"iteraction_version_plot": [], "date_range": date_range, "version_id": version_id,
                     "month_num": month_num}}
        if version_id > 0:
            for each_index in range(month_num -1, -1, -1):
                # 当前月份
                first_mouth_num = date.today().month - each_index
                # 指定的子系统获取每个月新增的Bug数据
                each_mouth_add_data = cursor.search_alone(
                    construct_verison_bug_each_mouth_add_histogram_sql(version_id, first_mouth_num))
                # 指定的子系统获取每个月关闭的Bug数据
                each_mouth_closed_data = cursor.search_alone(
                    construct_version_bug_each_mouth_closed_line_sql(version_id, first_mouth_num))
                # 数据组装
                json_returns['data']['iteraction_version_plot'].append(
                    {
                        "mouth": f"{first_mouth_num if first_mouth_num > 0 else (first_mouth_num + 12)}月",
                        "Bug_trend_histogram_add_num": each_mouth_add_data[0]['count'],
                        "Bug_trend_line_closed_num": each_mouth_closed_data[0]['count']
                    }
                )
        else:
            return HttpResponseBadRequest(content=b'request is a bad request')
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


# 三级页面-子系统详情页切换到：迭代版本用例统计图
def IterationCasePlot(request):
    """
        子系统迭代版本用例趋势图表
    :param request:
    :return:
    """

    if request.method == 'GET':
        # 获取get请求带的参数
        version_id = int(request.GET.get('version_id', -1))
        print(f'requrest params: {version_id}')
        date_range = int(request.GET.get('date_range', 7))
        month_num = int(request.GET.get('month_num', 6))
        print(f'requrest params: {version_id, date_range, month_num}')
        json_returns = {
            "data": {"version_case_trend_histogram": [], "date_range": date_range, "version_id": version_id,
                     "month_num": month_num}}


        if version_id > 0:
            for each_index in range(month_num -1, -1, -1):
                # 当前月份
                first_mouth_num = date.today().month - each_index
                each_month_version_case_status_statistics_results = cursor.search_alone(
                    construct_verison_case_histogram_each_month(version_id, first_mouth_num)
                )
                json_returns['data']['version_case_trend_histogram'].append(
                    {
                        "mouth": f"{first_mouth_num if first_mouth_num > 0 else (first_mouth_num + 12)}月",
                        "case_pass": each_month_version_case_status_statistics_results[0].get('pass', 0),
                        "case_failed": each_month_version_case_status_statistics_results[0].get('fail', 0),
                        "case_blocked": each_month_version_case_status_statistics_results[0].get('blocked', 0)
                    }
                )
        else:
            return HttpResponseBadRequest(content=b'request is a bad request')
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



# 四级页面-迭代版本详情页跳转到：测试单详情页
def iterationVersionTestTaskExtension(request):
    """
        "一个子系统对应多个迭代版本，迭代版本包含多个测试单"
        某个项目的子系统的迭代版本包含的测试单统计的详情
    :param request:
    :return:
    """

